package com.lazyframework.commons.support;

import lombok.extern.slf4j.Slf4j;
import org.reflections.Reflections;

import java.util.*;

@Slf4j
public final class ResponseStatusHelper {

    private static boolean initialized = false;

    private static final Map<Integer, String> STATUS_MAP = new TreeMap<>();

    private static String[] DEFAULT_SCAN_PACKAGES = { "com.lazyframework" };

    private ResponseStatusHelper() {}

    public static Map<Integer, String> getAllStatus() {
        if (STATUS_MAP.isEmpty()) {
            init();
        }
        return STATUS_MAP;
    }

    public static void init(String... scanPackages) {
        if (initialized) {
            return;
        }
        synchronized (ResponseStatusHelper.class) {
            List<String> scanList = new ArrayList<>();
            scanList.addAll(Arrays.asList(scanPackages));
            scanList.addAll(Arrays.asList(DEFAULT_SCAN_PACKAGES));
            scanList.forEach(ResponseStatusHelper::scan);
            initialized = true;
        }
    }

    private static void scan(String prefix) {
        Reflections reflections = new Reflections(prefix);
        Set<Class<? extends ResponseStatus>> types = reflections.getSubTypesOf(ResponseStatus.class);
        try {
            for (Class<? extends ResponseStatus> clazz : types) {
                ResponseStatus[] statuses = clazz.getEnumConstants();
                for (ResponseStatus status : statuses) {
                    int value = status.value();
                    String reasonPhrase = status.reasonPhrase();
                    STATUS_MAP.put(value, reasonPhrase);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

}
